from model import Category

class PositionManager(object):
    """
    """
    def __update_other_position(self, category, position, up):
        '''
        '''
        # create a query to find a category
        query = Category().all()

        # retrieve the category to update
        query.filter('language =', category.language)
        query.filter('position =', position)

        #
        for c in query:

            # category already updated, we want to update the other
            if not c.key() == category.key():

                #
                if up:
                    #
                    c.position = position + 1

                else:
                    #
                    c.position = position - 1

                #
                c.put()

    def position(self, category_key, up):
        '''
        '''
        # get the category obj
        category = Category().get(category_key)

        # get the current position for update
        position = category.position

        #
        updated = False

        #
        if up and position > 1:
            #
            position -= 1

            #
            updated = True

        # retrieve the number of categories for the same language
        query = Category().all()
        query.filter('language =', category.language)
        # count
        number_of_categories = query.count()

        if not up and position < number_of_categories:
            #
            position += 1

            #
            updated = True

        if updated:
            #
            category.position = position

            # update the db
            category.put()

            # update the other position
            self.__update_other_position(category, position, up)

        return category
